/**
 * 这里存放的是对token的操作
 */
import tokenStore from "store2";
import { getAccessTokenByCloud, getRefreshTokenByCloud } from "@/apis/Tokens";
import { getReqDataNew } from "./http";
import { successDataType, failDataType } from "CustomTypes";
import { getAccount, logout } from "./account";
import { isEqual } from "lodash";

// 千万不能用这个，没有记忆功能的！刷新就没了！
// const tokenStore = namespace("TokenCustom");
const accessTokenName = "access_token_custom";
const refreshTokenName = "refresh_token_custom";

/**
 * 是否有 accessToken
 */
export const hasAccessToken = (): boolean => tokenStore.has(accessTokenName);
/**
 * 是否有 refreshToken
 */
export const hasRefreshToken = (): boolean => tokenStore.has(refreshTokenName);
/**
 * 设置 accessToken
 */
export const setAccessToken = (data: string): void =>
  tokenStore.set(accessTokenName, data, true);

/**
 * 获取 accessToken
 */
export const getAccessToken = (): string => tokenStore.get(accessTokenName);
/**
 * 设置 refreshToken
 */
export const setRefreshToken = (data: string): void =>
  tokenStore.set(refreshTokenName, data, true);
/**
 * 获取 refreshToken
 */
export const getRefreshToken = (): string => tokenStore.get(refreshTokenName);
/**
 * 初始化accessToken
 */
export const initAccessToken = async (account: string): Promise<void> => {
  if (hasAccessToken()) return;
  const result = await getAccessTokenByCloud(account);
  const { flag, data } = getReqDataNew(result);
  if (!flag) return;
  // 获取accessToken成功
  const {
    data: { token }
  } = data as successDataType;
  setAccessToken(token);
};
/**
 * 初始化refreshToken
 */
export const initRefreshToken = async (account: string): Promise<void> => {
  if (hasRefreshToken()) return;
  const result = await getRefreshTokenByCloud(account);
  const { flag, data } = getReqDataNew(result);
  if (!flag) return;
  const {
    data: { token }
  } = data as successDataType;
  setRefreshToken(token);
};
/**
 * 进入页面就运行的token操作
 */
export const initTokens = async (): Promise<void> => {
  const account = getAccount();
  await initAccessToken(account);
  await initRefreshToken(account);
};
/**
 * 删除 accessToken
 */
export const removeAccessToken = (): void => tokenStore.remove(accessTokenName);
/**
 * 删除 refreshToken
 */
export const removeRefreshToken = (): void =>
  tokenStore.remove(refreshTokenName);
/**
 * 检查http返回的accessToken的信息，基本上是检查错误信息。
 */
export const checkAccessTokenMsg = (data: failDataType): boolean => {
  const { status, msg } = data;
  if (
    isEqual(1, status) &&
    isEqual(msg.name, "TokenExpiredError") &&
    isEqual(msg.message, "jwt expired")
  ) {
    logout();
    return false;
  } else {
    return true;
  }
};
